package dao

import (
	"errors"
	"fmt"
	__ "hospital-srv/basic/proto"
	"hospital-srv/handler/models"
	"strings"
	"time"
)

// 添加一级评论
// inits.HealthDB.Collection("product_comments")
// 一级评论添加
func ProductCommentAdd(in *__.ProductCommentsAddReq) (*models.ProductComments, error) {
	var user models.User
	err := user.GetUserInfoById(int(in.UserId))
	if err != nil {
		return nil, fmt.Errorf("获取用户信息失败: %w", err)
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在")
	}

	var goods models.Goods
	goods.Id = uint32(in.ProductId)
	err = goods.GoodsDetails()
	if err != nil {
		return nil, fmt.Errorf("获取商品信息失败: %w", err)
	}
	if goods.Id == 0 {
		return nil, fmt.Errorf("商品不存在")
	}

	// 1. 完善参数验证
	if in.UserId <= 0 {
		return nil, errors.New("用户ID无效（必须为正数）")
	}
	if in.ProductId <= 0 {
		return nil, errors.New("商品ID无效（必须为正数）")
	}
	if strings.TrimSpace(in.Content) == "" {
		return nil, errors.New("评论内容不能为空")
	}
	if in.Rating < 1 || in.Rating > 5 {
		return nil, errors.New("评分无效（必须为1-5星）")
	}

	// 2. 构造评论结构体
	now := time.Now().UTC()
	productComment := &models.ProductComments{
		Id:        in.Id,
		ProductId: in.ProductId,                  //商品id
		UserId:    in.UserId,                     // 若输入是正数，转换安全 评论的用户id
		UserName:  user.Nickname,                 //评论的用户昵称
		Content:   strings.TrimSpace(in.Content), // 去除首尾空格 评论的内容
		Rating:    in.Rating,                     // 评分
		CreatedAt: now,
	}

	// 3. 写入数据库
	if err := productComment.ProductCommentsCreate(); err != nil {
		return nil, fmt.Errorf("评论写入Mongo失败: %w", err) // 使用%w包裹原始错误，便于错误链追踪

	} // 假设方法名改为Create（更简洁）
	return productComment, nil
}

// 二级评论添加
func CommentReplyAdd(in *__.CommentReplyAddReq) (*models.CommentReply, error) {
	var user models.User
	err := user.GetUserInfoById(int(in.UserId))
	if err != nil {
		return nil, fmt.Errorf("获取用户信息失败: %w", err)
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	var productComments models.ProductComments
	productComments.Id = in.CommentId
	err = productComments.ProductCommentsDetails()
	if err != nil {
		return nil, fmt.Errorf("获取一级评论信息失败: %w", err)
	}
	if productComments.Id == 0 {
		return nil, fmt.Errorf("一级评论不存在")
	}

	commentReply := models.CommentReply{
		Id:        in.Id,
		CommentId: in.CommentId,  //一级评论id
		UserId:    in.UserId,     //评论的用户id
		UserName:  user.Nickname, //评论的用户昵称
		Content:   in.Content,    //评论的内容
		CreatedAt: time.Now(),
		IsDeleted: false,
	}
	if err := commentReply.CommentReplyCreate(); err != nil {
		return nil, fmt.Errorf("二级评论写入Mongo失败: %v", err)
	}
	return &commentReply, nil
}

func GetCommentsByProductId(in *__.GetCommentsByProductIdReq) ([]*__.ProductComment, error) {
	var comment models.ProductComments      //一级评论
	var commentList []*__.ProductComment    //一级评论
	var commentReply models.CommentReply    //二级评论
	var commentReplyList []*__.CommentReply //二级评论

	comment.ProductId = in.ProductId                 //商品id
	err := comment.ProductCommentsProductIdDetails() //一级评论详情
	if err != nil {
		return nil, fmt.Errorf("获取一级评论信息失败: %w", err)
	}
	if comment.Id == 0 {
		return nil, fmt.Errorf("一级评论不存在")
	}

	commentReply.CommentId = comment.Id
	//二级评论查找
	replyFind, err := commentReply.CommentReplyFind()
	if err != nil {
		return nil, err
	}

	for _, reply := range replyFind {
		if reply.CommentId == comment.Id {
			commentReplyList = append(commentReplyList, &__.CommentReply{
				Id:        reply.Id,
				CommentId: reply.CommentId,
				UserId:    reply.UserId,
				UserName:  reply.UserName,
				Content:   reply.Content,
			})
		}
	}

	comment.ProductId = in.ProductId
	find, err := comment.ProductCommentsFind() //一级评论查找
	if err != nil {
		return nil, err
	}

	//一级评论展示
	for _, comments := range find {
		commentList = append(commentList, &__.ProductComment{
			Replies:   commentReplyList,
			Id:        comments.Id,
			ProductId: comments.ProductId,
			UserId:    comments.UserId,
			UserName:  comments.UserName,
			Content:   comments.Content,
			Rating:    comments.Rating,
		})
	}
	return commentList, nil
}
